<!DOCTYPE html>
<#assign secSelect = JspTaglibs["http://www.casic304.cn/secSelect"] />
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理/编辑页面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${ctx}/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="${ctx}/systemStatic/style/admin.css">
    <link rel="stylesheet" href="${ctx}/extends/zTree_v3/css/zTreeStyle/zTreeStyle.css"/>
    <link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>
    <link rel="stylesheet" href="${ctx}/css/public.css">
    <style>
        .layui-layout-body{overflow: auto;}
    </style>
    <script type="text/javascript">
        var __ctx = "${ctx}";
    </script>
</head>
<body>
    <div class="layui-row">
        <div class="layui-form" action="" lay-filter="userForm" onsubmit="return false;">
            <div class="layui-tab layui-tab-card" style="height: 505px;overflow-y: auto;margin-top: 0;">
                <ul class="layui-tab-title">
                    <li class="layui-this">基本信息</li>
                    <li >组织选择</li>
                    <li>上级配置</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <table class="table-detail">
                            <tr>
                                <td rowspan="12" style="width:36%">
                                    <div style="text-align:center;margin-top:10px">
                                        <button type="button" id="addPictures" class="layui-btn layui-btn-sm "> <i class="layui-icon">&#xe67c;</i>上传图片</button>
                                        <button type="button" id="delPictures" class="layui-btn layui-btn-sm layui-btn-danger"> <i class="layui-icon">&#xe640;</i>删除图片</button>
                                    </div>

                                    <div style="margin-top:10px;text-align:center">
                                        <img src="<#if (picture!='' && picture!=null)>${picture}<#else>${ctx}/systemStatic/style/res/male.jpg</#if>" alt="加载失败"
                                             style="width:270px;height: 360px" class="imgShow">
                                        <input type="hidden" value="" name="picture" id="picture">
                                    </div>
                                </td>
                                <th style="width:16%;border-bottom:none;border-right:none;background: #f2f2f2;">账号:<span style="color:red;">*</span></th>
                                <td style="width:100%;border-bottom:none;"><input type="text" class="layui-input" name="account" lay-verify="required|names" maxlength="20" <#if userId??>disabled</#if>></td>
                            </tr>
                            <#if !(userId??)>
                                <tr class="passdis">
                                    <th style="border-bottom:none;border-right:none;background: #f2f2f2;">密码:<span style="color:red">*</span></th>
                                    <td style="border-bottom:none;"><input type="password" name="password" placeholder="请输入密码" autocomplete="off" lay-verify="required|pass"
                                               class="layui-input" maxlength="33" style="display:inline-block">
                                        <table class="pwdLever">
                                            <tr>
                                                <td>弱</td>
                                                <td>中</td>
                                                <td>强</td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </#if>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">用户姓名:<span style="color:red">*</span></th>
                                <td style="border-bottom:none;"><input type="text" name="fullName" autocomplete="off" class="layui-input" lay-verify="required|names"
                                           maxlength="33"></td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">用户性别:</th>
                                <td style="padding-left:6px;border-bottom:none;">
                                    <input type="radio" name="sex" value="1" title="男">
                                    <input type="radio" name="sex" value="0" title="女" checked>
                                </td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">身份证号:</th>
                                <td style="border-bottom:none;"><input type="text" name="idCard" autocomplete="off" class="layui-input" maxlength="18" lay-verify="idCard">
                                </td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">密级:</th>
                                <td style="border-bottom:none;">
                                    <@secSelect.sec_select data_src=2 name="privacyLevel"/>
                                    <!--<select name="privacyLevel" style="height:22px">
                                        <option value="0">非密</option>
                                        <option value="1">内部</option>
                                        <option value="2">一般</option>
                                        <option value="3">重要</option>
                                        <option value="4">核心</option>
                                    </select>-->
                                </td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">排序:</th>
                                <td style="border-bottom:none;"><input type="text" class="layui-input" name="sortNumber" ></td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">入职时间:</th>
                                <td style="border-bottom:none;"><input type="text" id="dataTest" placeholder="yyyy-MM-dd" name="entryDate"
                                           autocomplete="off"
                                           class="layui-input entrydate"></td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">员工状态:</th>
                                <td style="border-bottom:none;">
                                    <select name="userStatus" style="height:22px">
                                        <option value="0">正式员工</option>
                                        <option value="1">试用员工</option>
                                        <option value="2">停薪留职</option>
                                        <option value="3">返聘</option>
                                        <option value="4">中转</option>
                                        <option value="5">离职</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">邮箱地址:</th>
                                <td style="border-bottom:none;"><input type="text" class="layui-input" name="email" lay-verify="email"></td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">手机:</th>
                                <td style="border-bottom:none;"><input type="text" class="layui-input" name="mobile" lay-verify="mobile"></td>
                            </tr>
                            <tr>
                                <th style="border-bottom:none;border-right:none;background: #f2f2f2;">电话:</th>
                                <td style="border-bottom:none;"><input type="text" class="layui-input" name="phone" lay-verify="phone"></td>
                            </tr>
                        </table>
                    </div>


                    <div class="layui-tab-item">
                        <table>
                            <tr>
                                <td style="width:230px;display: block;" class="star_cont star_cont01">
                                    <div class="star_title"><p>所有组织</p></div>
                                    <ul id="orgJobSelection" class="ztree" style="background: #fff;overflow: auto"></ul>
                                </td>
                                <td style="width:100px;text-align: center" class="star_cont star_cont02">
                                    <button type="button" class="layui-btn addOrgData">添加</button>
                                </td>
                                <td style="display:list-item;list-style-type: none;background:#fff;" class="star_cont star_cont03">
                                    <div class="star_title"><p>已选组织</p></div>
                                    <table class="layui-table" id="orgJobSelectionTable" lay-filter="orgJobSelectionTable" style="margin:0 auto;">

                                        <thead>
                                        <tr>
                                            <th>组织名称</th>
                                            <th>是否主组织</th>
                                            <th>是否主要负责人</th>
                                            <th>操作</th>
                                        </tr>
                                        </thead>
                                        <tbody id="orgJobSelectiontbody">

                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="layui-tab-item">
                        <div class="manOfsub">
                            <span class="higherLevel colorSwitch">上级</span>
                            <div style="width: 76%;display: inline-block;">
                                <input type="" id="superiorConfiguration" value=""
                                       style="width:89%;margin-left: 20px;height: 40px;font-size: 18px;">
                                <i class="layui-icon layui-icon-more layui-btn"></i>
                            </div>
                        </div>
                        <div name="userSelector1" style="overflow: hidden;display: none" hidden>
                            <div class="ccpui-leftTree">
                                <span class="seltit">按组织查找</span>
                                <ul id="treeSelectUsers" class="ztree ccpui-selector" style="height:370px;"></ul>
                            </div>
                            <div class="ccpui-centerTree">
                                <div class="filter-table" style="position: relative;">
                                    <table class="layui-hide" id="userselectorAdd" lay-filter="userselectorAdd"></table>
                                    <div style="height: 420px;overflow: auto;position:absolute;right:-30px;top:-10px;width:30%">
                                        <table class="layui-table" id="app">
                                            <thead>
                                            <tr>
                                                <th>已选择</th>
                                            </tr>
                                            </thead>
                                            <tbody class="contentDiv">
                                            <tr>
                                                <td></td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="bottom" style="position: absolute;bottom:15px;left:375px;z-index: 666">
                                <button type="button" class="layui-btn saveData">保存</button>
                                <button type="button" class="layui-btn cancelData">撤销</button>
                                <button type="button" class="layui-btn layui-btn-danger cancelDatas">取消</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item" style="margin:0;">
                <div style="text-align: center">
                    <a lay-submit lay-filter="formUserkeep" class="layui-btn btn-n">保存</a>
                    <a class="layui-btn btn-n layui-btn-danger btn-back">取消</a>
                    <!--				<button type="reset" class="layui-btn layui-btn-primary">重置</button>-->
                </div>
            </div>
        </div>
    </div>
    <script type="text/html" id="headermanagementUseradd">
        <div class="layui-btn-container">
            <a class="layui-btn layui-btn-sm" lay-event="query">
                <i class="layui-icon">&#xe615;</i>
                <span>查询</span>
            </a>
        </div>
        <form class="layui-form" action="" lay-filter="headManagementUserForm" style="margin-top:10px">
            <div class="table-top-filter">
                <div class="table-filter-alone">
                    <label class="layui-form-label">姓名:</label>
                    <input style="width:180px" type="text" class="layui-input queryNames filter-value"
                           name="Q_fullName_SL"/>
                </div>
            </div>
        </form>
    </script>
    <script type="text/html" class="orgselectRight">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
    <!--<script type="text/html" id="checkboxIsCharge">-->
        <!--<input type="checkbox" name="lock" value="{{d.isCharge}}" lay-filter="checkboxIsCharges" title="是" {{ d.isCharge== 1 ? 'checked' : '' }}>-->
    <!--</script>-->
    <script src="${ctx}/extends/jquery.min.js" type="text/javascript"></script>
    <script src="${ctx}/public/component.js" type="text/javascript"></script>
    <script src="${ctx}/layui/layui.js"></script>
    <script src="${ctx}/extends/zTree_v3/js/jquery.ztree.all.min.js" type="text/javascript"></script>
    <script src="${ctx}/extends/zTree_v3/js/jquery.ztree.exhide.min.js" type="text/javascript"></script>
    <script>
        layui.config({
            base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
        }).extend({
            index: 'index' //主入口模块
        }).use(['index','form', 'layer', 'laydate', 'upload', 'setter', 'table', 'commons', 'totalFilter','util'], function () {
            var form = layui.form, layer = layui.layer, laydate = layui.laydate, upload = layui.upload,
                totalFilter = layui.totalFilter,util=layui.util,$=layui.jquery,
                setter = layui.setter, table = layui.table, commons = layui.commons;
            var userId = '${userId}';//修改
            var selectOrgId = '${selectOrgId}';//新增
            var arr = [];//上级配置   用户选择器全部数据数组
            var OrgId;//组织岗位选择
            // var OrgIds;//组织岗位选择复用
            // var indexData;//是否主岗位
            // var superConfigArr = [];//上级json数组
            // var superConfigData = [];//上级配置   用户选择器userid数组
            form.render();
            form.verify(commons.formVerify);
            //日期
            laydate.render({
                elem: '#dataTest',
                theme: 'molv'
            });
            //监听提交    修改数据
            if (userId) {
                //监听提交
                form.on('submit(formUserkeep)', function (data) {
                    var isaccess=valIsPriOrg();
                    if(!isaccess){
                        layer.alert("必须包含一个主组织！");
                        return ;
                    }
                    data.field.userId = userId;
                    var idinputs=$('input[name="userorgid"]');
                    var orgidArr=new Array();
                    idinputs.each(function () {
                        orgidArr.push($(this).val());
                    });
                    //debugger;
                    data.field.orgId = orgidArr.join(",");
                    var idinputs=$('input[name="isCharge"]:checked');
                    var orgidArr=new Array();
                    idinputs.each(function () {
                        orgidArr.push($(this).val());
                    });
                    data.field.isCharge = orgidArr.join(",");
                    var primayOrgId=$('input:radio[name="ispriOrg"]:checked').val();
                    data.field.primayOrgId = primayOrgId;
                    data.field.superiorIds = superConfigData;
                    delete data.field.file;
                    var data_json = JSON.stringify(data.field);


                    $.ajax({
                        url: serverPath.systemPath + setter.sysLinkPath + "sysUser/add",
                        type: "POST",
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify(data.field),
                        success: function (data) {
                            if (commons._filterRecord(data)) {
                                layer.alert(data.msg, function (index) {
                                    layer.close(index);
                                    parent.layui.table.reload('userListTable', {where:{orgId: selectOrgId},page: {curr: 1}});
                                    parent.layui.totalFilter.init('userListTable');
                                    parent.window.Initialization();
                                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                                });
                            } else {
                                layer.alert(data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert("保存失败！" + XMLHttpRequest.status);
                        }
                    });
                });
                var entity = eval('(${sysUser})');
                var time = util.toDateString(entity.entryDate,'yyyy-MM-dd');
                form.val('userForm', {
                    "account": entity.account,// "name": "value"
                    "entryDate": time,
                    "idCard": entity.idCard,//复选框选中状态
                    "fullName": entity.fullName,
                    "sex": entity.sex,
                    "userStatus": entity.userStatus,
                    "email": entity.email,
                    "mobile": entity.mobile,
                    "phone": entity.phone,
                    "picture": entity.picture,
                    "privacyLevel":entity.privacyLevel,
                    "sortNumber":entity.sortNumber
                })

            } else {
                var addbut = true;
                //新增数据
                form.on('submit(formUserkeep)', function (data) {

                    var isaccess=valIsPriOrg();
                    if(!isaccess){
                        layer.alert("必须包含一个主组织！");
                        return ;
                    }
                    if(!addbut){
                        layer.alert("正在保存，请稍后。。");
                        return ;
                    }
                    addbut = false;


                    // if (selectOrgId) {
                    //     data.field.orgId = selectOrgId;
                    // } else {
                    //     data.field.orgId = "";
                    // }
                    //
                    // if (indexData) {
                    //     var isChargeData = [];
                    //     isChargeData.push(indexData);
                    //     data.field.isCharge = isChargeData;
                    // }
                    // if (OrgIds) {
                    //     var ds = [];
                    //     ds.push(OrgIds);
                    //     data.field.posId = ds;
                    //     data.field.isPrimary = OrgIds;
                    // }

                    var idinputs=$('input[name="userorgid"]');
                    var orgidArr=new Array();
                    idinputs.each(function () {
                        orgidArr.push($(this).val());
                    });
                    data.field.orgId = orgidArr.join(",");
                    var idinputs=$('input[name="isCharge"]:checked');
                    var orgidArr=new Array();
                    idinputs.each(function () {
                        orgidArr.push($(this).val());
                    });
                    data.field.isCharge = orgidArr.join(",");
                    var primayOrgId=$('input:radio[name="ispriOrg"]:checked').val();
                    data.field.primayOrgId = primayOrgId;
                    data.field.superiorIds = superConfigData;
                    delete data.field.file;
                    var data_json = JSON.stringify(data.field);


                    // return;
                    $.ajax({
                        url: serverPath.systemPath + setter.sysLinkPath + "sysUser/add",
                        type: "POST",
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify(data.field),
                        success: function (data) {
                            if (commons._filterRecord(data)) {
                                layer.alert(data.msg, function (index) {
                                    layer.close(index);
                                    parent.layui.table.reload('userListTable', {where:{orgId: selectOrgId},page: {curr: 1}});
                                    parent.layui.totalFilter.init('userListTable');
                                    parent.window.Initialization();
                                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                                });
                            } else {
                                layer.alert(data.msg);
                            }
                            addbut = true;
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert("保存失败！" + XMLHttpRequest.status);
                            addbut = true;
                        }
                    });
                });
            }


            function valIsPriOrg(){
                var isselect= $('input:radio[name="ispriOrg"]:checked').val();
                if(isselect==null){
                    return  false;
                }else{
                    return true;
                }
            }
            function contHeight(){
                var allW = $(window).width();
                var allH = $(window).height();
                var btnHeight = $(".btnBox").height()+30;
                var titleHeight = $(".layui-tab-title").height();
                var contH = allH-btnHeight-titleHeight-30;
                //$(".layui-tab-content").css("height",)
                $(".star_cont").css("height",contH).css("overflow","auto");
                $(".layui-tab-content,.layui-tab-item ").css("height",contH).css("overflow","auto");
                $(".star_cont03").css("width",allW-$(".star_cont01").width()-$(".star_cont02").width()-20);
                $("#orgJobSelection").css("height",contH-51).css("overflow","auto");
            }
            $(window).resize(function(){
                contHeight();
            })
            // $(".btn-save").click(function () {
            //     parent.layer.close(parent.layer.getFrameIndex(window.name));
            // });

            $(".btn-back").click(function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });
            //图片上传
            var uploadInst = upload.render({
                elem: '#addPictures' //绑定元素
                ,url: serverPath.systemPath + setter.sysLinkPath +'attachFile/fileUpload' //上传接口
                ,accept: 'images' //允许上传的文件类型
                ,size: 51200
                ,exts:'jpg|png|jpeg'
                ,done: function(ret){
                    //上传完毕回调
                    if(commons._filterRecord(ret)){
                        if(ret.data){
                            var fileOne = ret.data.fileList[0];
                            var fileId = fileOne.fileId;
                            var path = serverPath.formPath + setter.sysLinkPath +'attachFile/getFileById?fileId='+fileId;
                            $('.imgShow').attr("src",path);
                            $('#picture').val(path);
                        }
                    }else{
                        layer.alert(ret.msg);
                    }
                }
            });
            $('#delPictures').click(function () {
                $("#picture").val("");
                $(".imgShow").attr("src",serverPath.systemPath+"/systemStatic/style/res/male.jpg");
            });
            //密码实时验证
            $("input[name='password']").keyup(function () {
                var num = this.value;
                commons.pwdChangenum(commons.pwdChange(num));
            });

            //上级配置页面
            orgUpZtrees();
            function orgUpZtrees() {
                $.ajax({
                    url: serverPath.systemPath + setter.sysLinkPath + "sysOrg/list",
                    type: "get",
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (data) {
                        if (commons._filterRecord(data)) {
                            var zNodes = data.data;
                            var setting = {
                                callback: {
                                    onClick: onClickUser
                                }
                            };
                            // var setting = {
                            //     view: {
                            //         showLine: false,
                            //         nameIsHTML: true, //允许name支持html
                            //         selectedMulti: false
                            //     },
                            //     edit: {
                            //         enable: false,
                            //         editNameSelectAll: false
                            //     },
                            //     data: {
                            //         simpleData: {
                            //             enable: true,
                            //             idKey:"orgId",
                            //             pIdKey:"orgSupId"
                            //         }
                            //     },
                            //     callback: {
                            //         onClick: onClickUser,
                            //     }
                            // };
                            $.fn.zTree.init($('#treeSelectUsers'), setting, zNodes);
                        } else {
                            layer.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                    }
                });
            }

            $.ajax({//编辑上级配置
                url: serverPath.systemPath + setter.sysLinkPath + "userUnder/querySuperiorByUserId",
                type: "get",
                contentType: 'application/json',
                dataType: 'json',
                async: false,
                data: {userId: userId},
                success: function (data) {
                    if (commons._filterRecord(data)) {
                        var datas = "";
                        superConfigArr = [];
                        superConfigData = [];
                        for (var i = 0; i < data.data.length; i++) {
                            datas += data.data[i].underUserName + "，";
                            superConfigArr.push({
                                name: data.data[i].underUserName,
                                userId: data.data[i].userId
                            });
                            superConfigData.push(data.data[i].userId);
                        }

                        $("#superiorConfiguration").val(datas);
                    } else {
                        window.parent.layer.alert(data.msg);
                    }
                }
            });

            function onClickUser(event, treeId, treeNode, clickFlag) {
                selectOrgId = treeNode.orgId;
                var params = {};
                $(".layui-form .filter-value").each(function() {
                    params[this.name] = '';
                });
                params.orgId = treeNode.orgId;
                table.reload("userselectorAdd", {
                    where: params
                });
            }

            table.render({
                elem: '#userselectorAdd',
                method: 'get',
                url: serverPath.systemPath + setter.sysLinkPath + 'sysUser/list',
                page: true,
                height: 'full-168',
                where: {},
                defaultToolbar: ['filter', 'print'],
                toolbar: '#headermanagementUseradd',
                cols: [
                    [{type: 'checkbox'},
                        {field: 'userId', title: 'ID', sort: true, hide: true},
                        {field: 'fullName', title: '姓名', width: 210},
                        {field: 'orgName', width: 210, title: '所属组织'}
                    ]
                ]
            });
            table.on('toolbar(userselectorAdd)', function (obj) {
                switch (obj.event) {
                    case 'query':
                        var params = {};
                        $(".queryNames").each(function () {
                            params[this.name] = this.value;
                        });
                        table.reload("userselectorAdd", {
                            where: params
                        });
                        form.val('headManagementUserForm', params);
                        break;
                }
            });
            arr = superConfigArr;
            $(".contentDiv").html("");
            for (var i = 0; i < arr.length; i++) {
                $(".contentDiv").append("<tr><td>" + arr[i].name + " <i selectIds=" + "'" + arr[i].userId + "'" + "class='layui-icon' style='position:absolute;right:12px;cursor: pointer'>&#xe640;</i></td></tr>")
            }
            table.on('checkbox(userselectorAdd)', function (obj) {
                var data = obj.data;
                var sel = obj.checked; //复选框状态
                var allS = obj.type; //是否全选
                var msg = {
                    name: data.fullName,
                    userId: data.userId
                } //选中行的name值
                var arr_re = JSON.stringify(arr).indexOf(JSON.stringify(msg)); //判断有没有
                var arrAll = table.cache.userselectorAdd;
                //全选
                if (allS == 'all') {
                    if (sel) {
                        for (var i = 0; i < arrAll.length; i++) {
                            var msgs = {
                                name: arrAll[i].fullName,
                                userId: arrAll[i].userId
                            };
                            var arr_res = JSON.stringify(arr).indexOf(JSON.stringify(msgs));
                            if (arr_res == -1) {
                                arr.push(msgs)
                            }
                        }
                    } else {
                        for (var i = 0; i < arr.length; i++) {
                            for (var j = 0; j < arrAll.length; j++) {
                                if (arr[i].userId == arrAll[j].userId) {
                                    arr.splice(i, 1);
                                    i--;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    if (sel) {
                        if (arr_re == -1) {
                            arr.push(msg);
                        }
                    } else {
                        if (arr_re != -1) {
                            for (var i = 0; i < arr.length; i++) {
                                if (arr[i].userId == msg.userId) {
                                    index = i;
                                }
                            }
                            arr.splice(index, 1);
                        }
                    }
                }
                $(".contentDiv").html("");
                for (var i = 0; i < arr.length; i++) {
                    $(".contentDiv").append("<tr><td>" + arr[i].name + " <i selectIds=" + "'" + arr[i].userId + "'" + "class='layui-icon' style='position:absolute;right:12px;cursor: pointer'>&#xe640;</i></td></tr>");
                }
            });

            $(".contentDiv .layui-icon").click(function () {
                $(this).parent().parent().remove();
                var delData = $(this).attr('selectIds');
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].userId == delData) {
                        arr.splice(i, 1);
                    }
                }
                table.reload("userselectorAdd", {
                    parseData: function (res) {
                        var _data = res.data;
                        if (_data.length > 0 && arr.length > 0) {
                            for (var i = 0; i < _data.length; i++) {
                                var _d = _data[i];
                                for (var j = 0; j < arr.length; j++) {
                                    var _td = arr[j];
                                    if (_d.userId === _td.userId) {
                                        _d.LAY_CHECKED = true;
                                    }
                                }
                            }
                        }
                    },
                    page: {curr: 1}
                });
            })

            //全部取消
            $(".bottom .cancelData").click(function () {
                $(".contentDiv").html("");
                arr = [];
                table.reload('userselectorAdd');
                return false;
            });
            $(".bottom .cancelDatas").click(function () {
                layer.close(UserIndex);
                return false;
            });
            //保存
            $(".bottom .saveData").click(function () {
                var data = "";
                superConfigData = [];
                for (var i = 0; i < arr.length; i++) {
                    data += arr[i].name + "，";
                    superConfigData.push(arr[i].userId);
                }
                $("#superiorConfiguration").val(data);
                layer.close(UserIndex);
                return false;
            });
            var UserIndex = "";//弹窗关闭
            $(".manOfsub .layui-icon-more").click(function () {
                UserIndex = layer.open({
                    type: 1,
                    area: ['980px', '500px'],
                    resize: false,
                    title: ['用户选择器', 'font-size:18px;'],
                    content: $("[name='userSelector1']"),
                    success: function () {
                        table.reload("userselectorAdd", {
                            parseData: function (res) {
                                var _data = res.data;
                                if (_data.length > 0 && arr.length > 0) {
                                    for (var i = 0; i < _data.length; i++) {
                                        var _d = _data[i];
                                        for (var j = 0; j < arr.length; j++) {
                                            var _td = arr[j];
                                            if (_d.userId === _td.userId) {
                                                _d.LAY_CHECKED = true;
                                            }
                                        }
                                    }
                                }
                            },
                            page: {curr: 1}
                        });
                    }
                });
            });

            //组织岗位选择
            orgZtrees();
            contHeight();
            function orgZtrees() {
                $.ajax({
                    url: serverPath.systemPath + setter.sysLinkPath + "sysOrg/list",
                    type: "get",
                    contentType: 'application/json',
                    dataType: 'json',
                    data: {
                        userId: userId,
                        orgId: selectOrgId
                    },
                    success: function (data) {
                        if (commons._filterRecord(data)) {
                            var zNodes = data.data;
                            var setting = {
                                view:{
                                    nameIsHTML: true
                                },
                                data: {
                                    key: {
                                        title: "orgName"
                                    },
                                    simpleData: {
                                        enable: true,
                                        idKey:"orgId",
                                        pIdKey:"orgSupId"
                                    }
                                },
                                callback: {
                                    onClick: onClickOrg,
                                }
                            };

                            //console.log(zNodes);

                            $.fn.zTree.init($('#orgJobSelection'), setting, zNodes);
                            $.fn.zTree.getZTreeObj("orgJobSelection").expandAll(true);
                        } else {
                            layer.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                    },
                });
            }

            function onClickOrg(event, treeId, treeNode, clickFlag) {
                OrgId = treeNode.id;
            }

            $(".layui-tab-item .addOrgData").click(function () {
                var  orgJobSelection=$.fn.zTree.getZTreeObj("orgJobSelection");
                var selectedNodes = orgJobSelection.getSelectedNodes();
                var node=selectedNodes[0];
                var len=$("input[name='userorgid'][value='"+node.orgId+"']").length;
                if(len==0){
                    //你要添加的html
                    var html = '<tr>'+
                        '<td>'+node.orgName+'</td>'+
                        '<td><input type="radio" name="ispriOrg" value="'+node.orgId+'"/><input type="hidden" name="userorgid" value="'+node.orgId+'"/></td>'+
                        '<td><input type="checkbox" name="isCharge" lay-skin="primary" value="'+node.orgId+'"></td>'+
                        '<td><button class="layui-btn orgdel">移除</button></td>'+
                        '</tr>';
                    //添加到表格最后
                    $("#orgJobSelectiontbody").append( html);
                    form.render();
                }else{
                    layer.alert("已经存在相同的组织！");
                }
            });

            $(document).on("click",".orgdel",function(){
                $(this).parent().parent().remove();
            });

            initorginfo();
            function initorginfo(){
                $.ajax({
                    url: serverPath.systemPath + setter.sysLinkPath + 'userPosition/queryByUserIdOrPosId',
                    type: "get",
                    contentType: 'application/json',
                    dataType: 'json',
                    data: {
                        userId: userId,
                        selectOrgId:selectOrgId
                    },
                    success: function (data) {
                        if (commons._filterRecord(data)) {
                            var htmlArr=new Array();
                            for(var i=0;i<data.data.length;i++){

                                var html = '<tr>'+
                                    '<td>'+data.data[i].orgName+'</td>'+
                                    '<td><input type="radio" name="ispriOrg" value="'+data.data[i].orgId+'"  '+(data.data[i].isPrimary==1?'checked':'')+'  /><input type="hidden" name="userorgid" value="'+data.data[i].orgId+'"/></td>'+
                                    '<td><input type="checkbox" name="isCharge" lay-skin="primary"  value="'+data.data[i].orgId+'"  '+(data.data[i].isCharge==1?"checked":"")+'  /></td>'+
                                    '<td><button class="layui-btn orgdel">移除</button></td>'+
                                    '</tr>';
                                htmlArr.push(html);
                            }
                            //添加到表格最后
                            $("#orgJobSelectiontbody").append( htmlArr.join(" "));
                            form.render();
                        } else {
                            layer.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                    },
                });
            }

            // table.render({
            //     elem: '#orgJobSelectionTable',
            //     method: 'get',
            //     url: serverPath.systemPath + setter.sysLinkPath + 'userPosition/queryByUserIdOrPosId',
            //     page: false,
            //     height: 'full-144',
            //     where: {
            //         posId: "",
            //         userId: userId
            //     },
            //     cols: [
            //         [
            //             {
            //                 field: 'posId',
            //                 title: 'ID',
            //                 sort: true,
            //                 hide: true
            //             },
            //             {
            //                 field: 'orgName',
            //                 title: '组织名称',
            //                 width: 170
            //             }, {
            //             field: 'posName',
            //             width: 190,
            //             title: '岗位名称'
            //         },
            //             {
            //                 field: ' isPrimary',
            //                 width: 110,
            //                 title: '是否主岗位',
            //                 align: "center",
            //                 templet: function (d) {
            //                     return " <input type='radio' checked >"
            //                 }
            //             },
            //             {
            //                 field: 'isCharge',
            //                 width: 120,
            //                 title: '主要负责人',
            //                 align:'center',
            //                 templet: '#checkboxIsCharge'
            //             },
            //         ]
            //     ],
            //     done: function (d) {
            //         if (userId && d.data.length > 0) {
            //             OrgIds = d.data[0].posId;
            //         }
            //     },
            // });
            // //监听锁定操作
            // form.on('checkbox(checkboxIsCharges)', function (obj) {
            //     if (obj.elem.checked) {
            //         indexData = OrgIds
            //     } else {
            //         indexData = "";
            //     }
            // });

        })

    </script>

    <style>
        /*重构按钮*/
        .higherLevel{
            display: inline-block;
            height: 46px;
            line-height: 46px;
            padding: 0 18px;
            background-color: #009688;
            color: #fff;
            text-align: center;
            font-size: 18px;
            border-radius: 2px;
            width:18%
        }
    </style>
</body>
</html>